package org.example.translate_braille.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.example.translate_braille.entity.Photo;
import org.apache.commons.io.FileUtils;
import org.example.translate_braille.mapper.PhotoMapper;
import org.example.translate_braille.resdata.DataEnum;
import org.example.translate_braille.resdata.X;
import org.example.translate_braille.service.PhotoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.translate_braille.utils.TencentCosUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jacky
 * @since
 */
@Service
@Slf4j
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements PhotoService {

    @Autowired
    PhotoService photoService;


    @Override
    public X<Photo> showPhotoList(String userId) {
        try {
            //构造器
            QueryWrapper<Photo> queryable = new QueryWrapper<>();
            queryable.lambda()
                    .eq(Photo::getUserId, userId)
                    .eq(Photo::getIsDeleted,0)
                    .orderByDesc(Photo::getUploadTime)
            ;
            return X.ResData(DataEnum.SUCCESS, photoService.list(queryable));
        }catch(Exception e){
            return X.ResData(DataEnum.SELECT_FAIL, Convert.toStr(e));
        }
    }

    @Override
    public X<Photo> inOrUpPhoto(Photo photo,String picture,String picType) {
        //对收到的base64码进行解码得到图像
        byte[] decodeBase64 = Base64.decodeBase64(picture);
        System.out.println("图像base64解码为"+decodeBase64);
        File file;
        try {
            //利用当前的时间和原图像的后缀格式名（.jpg/.png）定义一个空的文件对象的文件名
            file = File.createTempFile(String.valueOf(System.currentTimeMillis()), picType);
            //FileUtil类是Apache Commons IO库里面的一个类，将解码后的图像写入到"file"图片文件对象中
            FileUtils.writeByteArrayToFile(file, decodeBase64);
            //上传原图到云对象存储
            String picUrl = TencentCosUtil.uploadfile(file, photo.getPhotoName());
            //指定post请求访问本地端口5000的"/base64_img"接口路径
            HttpResponse response3 = HttpRequest.post("http://127.0.0.1:5000/base64_img")
                    .form("img", picture)
                    .execute();
            System.out.println("python识别模块传回的是效果图的Base64码："+response3.body());
            //对python图像识别模块返回翻译效果图的base64码进行解码
            decodeBase64 = Base64.decodeBase64(response3.body());
            //文件命名、文件写入、文件上传到云存储的操作同上
            file = File.createTempFile(String.valueOf(System.currentTimeMillis()), picType);
            FileUtils.writeByteArrayToFile(file, decodeBase64);
            String translatedPicUrl = TencentCosUtil.uploadfile(file, photo.getPhotoName());
            System.out.println(translatedPicUrl);
            //将原图url和效果图的url封装在photo对象中
            photo.setSaveAddress(picUrl);
            photo.setTranslateAddress(translatedPicUrl);
            //用MP的底层封装好的insert和update语句的数据库插入记录方法将photo对象的属性信息存入数据库中
            photoService.saveOrUpdate(photo);
            //以上操作正常返回"请求成功"的状态码和效果图的url给接口方法
            return X.ResData(DataEnum.SUCCESS,translatedPicUrl);
        }catch(Exception e){
            //如果以上操作不成功返回"添加失败"的状态码和错误信息给接口方法
            return X.ResData(DataEnum.INSERT_FAIL, Convert.toStr(e));
        }
    }

    @Override
    public X<Photo> deletePhoto(Photo photo) {
        photo.setIsDeleted(1);
        return X.ResData(DataEnum.SUCCESS,photoService.saveOrUpdate(photo));
    }
}
